// 当DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 加载纪念日数据
    loadMemoryData();
});

// 加载纪念日数据
function loadMemoryData() {
    fetch('/data/memory.json')
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            // 初始化纪念日功能
            initMemory(data);
        })
        .catch(error => {
            console.error('获取数据出错:', error);
            showNotification('加载数据失败，请刷新页面重试', 'error');
        });
}

// 初始化纪念日功能
function initMemory(data) {
    // 计算在一起的天数
    calculateDaysTogether(data.relationshipStartDate);
    
    // 渲染时间线
    renderTimeline(data.memories);
    
    // 渲染即将到来的重要日子
    renderUpcomingEvents(data.upcomingEvents);
    
    // 初始化时间线动画
    initTimelineAnimation();
    
    // 初始化纪念日表单
    initMemoryForm();
    
    // 初始化纪念日照片查看
    initPhotoViewer();
}

// 计算在一起的天数
function calculateDaysTogether(startDateStr) {
    // 恋爱开始的日期
    const startDate = new Date(startDateStr);
    const today = new Date();
    
    // 计算相差的毫秒数并转换为天数
    const timeDiff = Math.abs(today.getTime() - startDate.getTime());
    const daysTogether = Math.floor(timeDiff / (1000 * 3600 * 24));
    
    // 更新页面上的天数显示
    const totalDaysElement = document.getElementById('total-days');
    if (totalDaysElement) {
        totalDaysElement.textContent = daysTogether;
    }
}

// 渲染时间线
function renderTimeline(memories) {
    const timelineContainer = document.querySelector('.timeline');
    if (!timelineContainer) return;
    
    // 清空现有内容
    timelineContainer.innerHTML = '';
    
    // 添加每个记忆
    memories.forEach(memory => {
        const timelineItem = document.createElement('div');
        timelineItem.className = `timeline-item ${memory.isSpecial ? 'special' : ''} memory-item`;
        timelineItem.setAttribute('data-id', memory.id);
        
        // 构建HTML内容
        timelineItem.innerHTML = `
            <div class="timeline-date">
                <div class="date">${formatDisplayDate(memory.date)}</div>
                <div class="days-ago">${memory.daysAgo}</div>
            </div>
            <div class="timeline-content">
                <div class="memory-icon"><i class="fas ${memory.icon}"></i></div>
                <div class="memory-details">
                    <h3>${memory.title}</h3>
                    <p>${memory.description}</p>
                    <div class="memory-photos">
                        ${memory.photos.map(photo => `<img src="${photo}" alt="${memory.title}">`).join('')}
                    </div>
                    <div class="memory-meta">
                        ${memory.tags.map(tag => `<div class="tag">#${tag}</div>`).join('')}
                    </div>
                </div>
            </div>
        `;
        
        timelineContainer.appendChild(timelineItem);
    });
}

// 渲染即将到来的重要日子
function renderUpcomingEvents(events) {
    const upcomingGrid = document.querySelector('.upcoming-grid');
    if (!upcomingGrid) return;
    
    // 清空现有内容
    upcomingGrid.innerHTML = '';
    
    // 添加每个事件
    events.forEach(event => {
        const eventCard = document.createElement('div');
        eventCard.className = 'upcoming-card upcoming-event-item';
        eventCard.setAttribute('data-id', event.id);
        
        // 构建HTML内容
        eventCard.innerHTML = `
            <div class="upcoming-date">
                <div class="month">${event.month}</div>
                <div class="day">${event.day}</div>
            </div>
            <div class="upcoming-info">
                <h3>${event.title}</h3>
                <p class="countdown">${event.countdown}</p>
                <div class="upcoming-actions">
                    <button class="btn btn-sm btn-outline">查看详情</button>
                    <button class="btn btn-sm btn-primary">设置提醒</button>
                </div>
            </div>
        `;
        
        upcomingGrid.appendChild(eventCard);
    });
    
    // 添加按钮事件监听
    addUpcomingEventsListeners();
}

// 为即将到来的事件添加事件监听
function addUpcomingEventsListeners() {
    // 查看详情按钮
    const detailButtons = document.querySelectorAll('.upcoming-actions .btn-outline');
    detailButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            const card = this.closest('.upcoming-event-item');
            const eventId = card.getAttribute('data-id');
            const eventTitle = card.querySelector('h3').textContent;
            
            showEventDetails(eventTitle, eventId);
        });
    });
    
    // 设置提醒按钮
    const reminderButtons = document.querySelectorAll('.upcoming-actions .btn-primary');
    reminderButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            const card = this.closest('.upcoming-event-item');
            const eventId = card.getAttribute('data-id');
            const eventTitle = card.querySelector('h3').textContent;
            
            setReminder(eventTitle, eventId);
        });
    });
}

// 初始化时间线动画
function initTimelineAnimation() {
    // 检查是否支持IntersectionObserver
    if ('IntersectionObserver' in window) {
        const options = {
            root: null,
            rootMargin: '0px',
            threshold: 0.1
        };
        
        const observer = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('visible');
                    observer.unobserve(entry.target);
                }
            });
        }, options);
        
        // 观察所有时间线项目
        document.querySelectorAll('.timeline-item').forEach(item => {
            observer.observe(item);
        });
    } else {
        // 如果不支持IntersectionObserver，则直接显示所有项目
        document.querySelectorAll('.timeline-item').forEach(item => {
            item.classList.add('visible');
        });
    }
}

// 初始化纪念日表单
function initMemoryForm() {
    const addMemoryBtn = document.getElementById('add-memory-btn');
    const memoryModal = document.getElementById('add-memory-modal');
    
    if (!addMemoryBtn || !memoryModal) return;
    
    // 点击添加纪念日按钮
    addMemoryBtn.addEventListener('click', function() {
        memoryModal.style.display = 'block';
    });
    
    // 关闭模态框
    const closeBtn = memoryModal.querySelector('.close');
    if (closeBtn) {
        closeBtn.addEventListener('click', function() {
            memoryModal.style.display = 'none';
        });
    }
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        if (event.target === memoryModal) {
            memoryModal.style.display = 'none';
        }
    });
    
    // 照片上传
    const photoUploadBtn = memoryModal.querySelector('.photo-upload button');
    const photoInput = memoryModal.querySelector('.photo-upload input[type=file]');
    
    if (photoUploadBtn && photoInput) {
        photoUploadBtn.addEventListener('click', function() {
            photoInput.click();
        });
        
        photoInput.addEventListener('change', function() {
            // 显示照片预览
            displayPhotoPreview(this.files);
        });
    }
    
    // 标签输入
    const tagsInput = memoryModal.querySelector('.tags-input input');
    const tagsList = memoryModal.querySelector('.tags-list');
    
    if (tagsInput && tagsList) {
        tagsInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && this.value.trim()) {
                e.preventDefault();
                addTag(this.value.trim());
                this.value = '';
            }
        });
    }
    
    // 添加标签函数
    function addTag(text) {
        if (!text) return;
        
        const tag = document.createElement('div');
        tag.className = 'tag';
        tag.innerHTML = `
            #${text} <i class="fas fa-times"></i>
        `;
        
        const removeBtn = tag.querySelector('i');
        removeBtn.addEventListener('click', function() {
            tag.remove();
        });
        
        tagsList.appendChild(tag);
    }
    
    // 保存纪念日
    const saveBtn = memoryModal.querySelector('.form-buttons .btn-primary');
    if (saveBtn) {
        saveBtn.addEventListener('click', function() {
            saveMemory();
        });
    }
}

// 显示照片预览
function displayPhotoPreview(files) {
    const previewContainer = document.querySelector('.upload-preview');
    if (!previewContainer) return;
    
    // 清空预览区域
    previewContainer.innerHTML = '';
    
    // 添加新预览
    Array.from(files).forEach((file, index) => {
        // 创建预览元素
        const preview = document.createElement('div');
        preview.className = 'preview-item';
        
        // 添加图片
        const img = document.createElement('img');
        img.src = URL.createObjectURL(file);
        preview.appendChild(img);
        
        // 添加删除按钮
        const removeBtn = document.createElement('div');
        removeBtn.className = 'preview-remove';
        removeBtn.innerHTML = '<i class="fas fa-times"></i>';
        removeBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            preview.remove();
        });
        
        preview.appendChild(removeBtn);
        previewContainer.appendChild(preview);
    });
}

// 保存纪念日
function saveMemory() {
    // 获取表单数据
    const title = document.querySelector('#add-memory-modal input[type="text"]').value.trim();
    const date = document.querySelector('#add-memory-modal input[type="date"]').value;
    const type = document.querySelector('#add-memory-modal select').value;
    const description = document.querySelector('#add-memory-modal textarea').value.trim();
    
    // 验证必填项
    if (!title) {
        showNotification('请输入纪念日名称', 'warning');
        return;
    }
    
    if (!date) {
        showNotification('请选择日期', 'warning');
        return;
    }
    
    // 在实际项目中，这里应该有一个AJAX请求发送数据到服务器
    // 为了演示，我们只显示成功通知
    
    showNotification('纪念日添加成功！', 'success');
    
    // 关闭模态框
    const memoryModal = document.getElementById('add-memory-modal');
    if (memoryModal) {
        memoryModal.style.display = 'none';
    }
    
    // 清空表单
    resetMemoryForm();
}

// 重置纪念日表单
function resetMemoryForm() {
    const form = document.querySelector('.memory-form');
    if (!form) return;
    
    // 重置输入框
    form.querySelector('input[type="text"]').value = '';
    form.querySelector('input[type="date"]').value = '';
    form.querySelector('select').selectedIndex = 0;
    form.querySelector('textarea').value = '';
    
    // 重置标签
    const tagsList = form.querySelector('.tags-list');
    if (tagsList) {
        tagsList.innerHTML = '';
    }
    
    // 重置提醒选项
    const checkboxes = form.querySelectorAll('input[type="checkbox"]');
    checkboxes.forEach(checkbox => {
        checkbox.checked = false;
    });
    
    // 清空照片预览
    const previewContainer = form.querySelector('.upload-preview');
    if (previewContainer) {
        previewContainer.innerHTML = '';
    }
}

// 初始化照片查看器
function initPhotoViewer() {
    // 给所有记忆照片添加点击事件
    document.querySelectorAll('.memory-photos img').forEach(img => {
        img.addEventListener('click', function() {
            showPhotoFullScreen(this.src);
        });
    });
}

// 显示全屏照片
function showPhotoFullScreen(src) {
    // 创建全屏查看容器
    const viewer = document.createElement('div');
    viewer.className = 'photo-viewer';
    
    // 添加照片
    viewer.innerHTML = `
        <div class="photo-viewer-content">
            <img src="${src}" alt="全屏照片">
            <button class="close-viewer"><i class="fas fa-times"></i></button>
        </div>
    `;
    
    // 添加到页面
    document.body.appendChild(viewer);
    
    // 防止滚动
    document.body.style.overflow = 'hidden';
    
    // 显示动画
    setTimeout(() => {
        viewer.classList.add('show');
    }, 10);
    
    // 关闭按钮事件
    const closeBtn = viewer.querySelector('.close-viewer');
    closeBtn.addEventListener('click', closeViewer);
    
    // 点击背景关闭
    viewer.addEventListener('click', function(e) {
        if (e.target === viewer) {
            closeViewer();
        }
    });
    
    // 按ESC键关闭
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeViewer();
        }
    });
    
    function closeViewer() {
        viewer.classList.remove('show');
        setTimeout(() => {
            viewer.remove();
            document.body.style.overflow = 'auto';
        }, 300);
    }
}

// 设置提醒
function setReminder(eventName, eventId) {
    // 在实际项目中，这里应该有更复杂的提醒设置逻辑
    // 这里只是简单地显示通知
    showNotification(`已为"${eventName}"设置提醒`, 'success');
}

// 显示事件详情
function showEventDetails(eventName, eventId) {
    // 在实际项目中，这里应该显示详细信息
    // 这里只是简单地显示通知
    showNotification(`正在查看"${eventName}"的详情`, 'info');
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <p>${message}</p>
            <button class="close-notification">&times;</button>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.classList.add('show');
    }, 10);
    
    // 自动关闭
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 3000);
    
    // 手动关闭
    notification.querySelector('.close-notification').addEventListener('click', () => {
        notification.classList.remove('show');
        setTimeout(() => {
            notification.remove();
        }, 300);
    });
}

// 格式化日期显示
function formatDisplayDate(dateStr) {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    
    return `${year}年${month}月${day}日`;
} 